<template>
	<div class="login-container">
		<div class="login-box">
			<div class="login-header">
				<h2>用户登录</h2>
			</div>
			<van-cell-group class="cell-group">
				<van-field label="账号" placeholder="请输入账号" v-model="loginForm.name" class="login-field"
					:placeholder-style="{ color: '#ccc' }" />
				<van-field label="密码" placeholder="请输入密码" type="password" v-model="loginForm.password"
					class="login-field" :placeholder-style="{ color: '#ccc' }" />
				<van-button @click="onClickLogin" type="primary" size="normal" block class="login-button"
					:loading="isLoading">
					{{ isLoading? '登录中...' : '登录' }}
				</van-button>
			</van-cell-group>
			<div class="goto">
				<van-button @click="onRegister" type="link" class="register-link">
					若还没有账号？点击前往注册
				</van-button>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		showToast
	} from 'vant';
	import {
		getUserLocal,
		setUserLocal,
		setTokenLocal
	} from "@/utils/auth.js";
	import {
		loginAPI
	} from "@/api/user.js";

	export default {
		data() {
			return {
				loginForm: {
					name: "",
					password: ""
				},
				isLoading: false
			};
		},

		mounted() {
			const user = getUserLocal();
			if (user) {
				this.loginForm.name = user.name;
			}
		},

		methods: {
			// 重试请求函数
			async retryRequest(requestFunction, maxRetries = 3) {
				let retries = 0;
				while (retries < maxRetries) {
					try {
						return await requestFunction();
					} catch (error) {
						retries++;
						if (retries === maxRetries) {
							throw error;
						}
						console.log(`请求失败，正在进行第 ${retries} 次重试...`);
					}
				}
			},

			// 处理用户登录
			async onClickLogin() {
				// 验证用户名和密码长度
				if (this.loginForm.name.length < 3 || this.loginForm.name.length > 20) {
					showToast("用户名长度必须在 3 到 20 个字符之间");
					return;
				}
				if (this.loginForm.password.length < 6 || this.loginForm.password.length > 30) {
					showToast("密码长度必须在 6 到 30 个字符之间");
					return;
				}

				this.isLoading = true;
				const params = this.loginForm;
				try {
					const result = await this.retryRequest(() => loginAPI(params));
					showToast({
						message: "登录成功！",
						duration: 1000
					});
					// 本地保存用户信息（id,name）保存 Token，调用 utils/auth.js 模块功能
					setTokenLocal(result.data.token);
					setUserLocal(result.data.user);
					// 登录成功后跳转到需要重定向的路径，默认是我的页面（user）
					let toPath = this.$route.params.redirect || "user";
					setTimeout(() => {
						this.$router.replace({
							path: toPath
						});
					}, 1000);
				} catch (error) {
					if (error.message === "用户名或密码错误") {
						showToast("用户名或密码错误，请重新输入");
					} else {
						showToast("登录失败，请稍后重试");
					}
					console.error('登录错误:', error);
				} finally {
					this.isLoading = false;
				}
			},

			// 处理用户注册
			onRegister() {
				// 跳转到注册页面
				this.$router.push({
					name: "register"
				});
			}
		}
	};
</script>

<style lang="less" scoped>
	@bg-color: #f9f9f9;
	@primary-color: #007bff;
	@secondary-color: #f0f0f0;
	@text-color: #333;
	@link-color: #007bff;
	@border-color: #e0e0e0;

	.login-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		background-color: @bg-color;
		animation: fadeIn 1s ease;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	.login-box {
		width: 350px;
		padding: 30px;
		background-color: #fff;
		border-radius: 15px;
		box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
		animation: slideIn 1s ease;
	}

	@keyframes slideIn {
		from {
			transform: translateY(-50px);
			opacity: 0;
		}

		to {
			transform: translateY(0);
			opacity: 1;
		}
	}

	.login-header {
		text-align: center;
		margin-bottom: 25px;
	}

	.login-header h2 {
		font-size: 28px;
		color: @text-color;
		font-weight: bold;
	}

	.cell-group {
		border: 1px solid @border-color;
		border-radius: 10px;
		padding: 20px;
	}

	.login-field {
		margin-bottom: 20px;
		border: none;
		border-bottom: 2px solid @secondary-color;
		padding-bottom: 10px;
		font-size: 16px;
		color: @text-color;
		transition: border-bottom-color 0.3s ease;

		&:focus {
			border-bottom-color: @primary-color;
		}
	}

	.login-button {
		margin-top: 20px;
		border-radius: 8px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
		padding: 12px;
		font-size: 18px;
		transition: all 0.3s ease;

		&:hover {
			background-color: darken(@primary-color, 10%);
			transform: translateY(-3px);
			box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
		}
	}

	.goto {
		margin-top: 20px;
		text-align: center;
		font-size: 14px;
		color: @text-color;
	}

	.register-link {
		color: @link-color;
		text-decoration: underline;
		transition: all 0.3s ease;

		&:hover {
			color: darken(@link-color, 10%);
		}
	}
</style>